package com.swak.fx.support.ui;

import java.lang.reflect.Method;

import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;

public class UITextFlow extends TextFlow implements UILifecycle {

	private static Method textLayoutMethod;
	{
		try {
			textLayoutMethod = TextFlow.class.getDeclaredMethod("getTextLayout");
			textLayoutMethod.setAccessible(true);
		} catch (Exception e) {
		}
	}

	// ================================================================================
	// Properties
	// ================================================================================
	private final String STYLE_CLASS = "ui-textflow";

	public UITextFlow() {
		super();
		init();
	}

	@Override
	public void initializeParts() {
		getStyleClass().add(STYLE_CLASS);
		this.setPrefHeight(USE_COMPUTED_SIZE);
		this.setPrefWidth(USE_COMPUTED_SIZE);
	}

	/**
	 * 处理溢出文本
	 * 
	 * @param width
	 */
	public void ellipsis() {
		this.ellipsis(-1);
	}

	/**
	 * 处理溢出文本
	 * 
	 * @param width
	 */
	public void ellipsis(double fontSize) {
		TextFlow text = this;
		double maxWidth = text.getMaxWidth();
		Bounds textsBounds = text.localToParent(text.getBoundsInLocal());
		double width = Math.max(textsBounds.getWidth(), maxWidth);
		double innerWidth = 0;
		double textWidth = -1;
		for (Node node : text.getChildren()) {
			double nodeWidth = node.prefWidth(-1);
			if (node instanceof Text) {
				nodeWidth = Math.max(nodeWidth, fontSize);
				textWidth = Math.max(textWidth, nodeWidth);
			}
			innerWidth += nodeWidth;
		}
		if (textWidth == -1) {
			textWidth = 7.3;
		}
		if (innerWidth > width) {
			width = width - Math.ceil(textWidth * 3);
			innerWidth = 0;
			for (Node node : text.getChildren()) {
				double nodeWidth = node.prefWidth(-1);
				if (innerWidth + nodeWidth > width) {
					node.setManaged(false);
					node.setVisible(false);
				} else {
					innerWidth += nodeWidth;
				}
			}
			text.getChildren().add(this.buildEllipsis());
		}
	}

	private Text buildEllipsis() {
		Text ellipsis = new Text("...");
		ellipsis.setTextAlignment(TextAlignment.JUSTIFY);
		ellipsis.getStyleClass().add("text");
		return ellipsis;
	}
}
